package net.oschina.simpleplus.redis;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

public class JRedisProxy implements JRedis {
	private JRedisShard jRedisShard;
	
	//private String masters;
	private List<JRedis> jRedises = new ArrayList<JRedis>();
	
	public JRedisProxy(String masters) {
		this(null, masters);
	}

	public JRedisProxy(JRedisShard jRedisShard, String masters) {
		this.jRedisShard = jRedisShard == null ? new DefaultJRedisShard() : jRedisShard;
		if(masters == null || "".equals(masters.trim())){
			throw new RuntimeException("masters config error!" + masters);
		}
		
		for(String uriStr : masters.split(",")){
			jRedises.add(new JRedisImpl(URI.create(uriStr)));
		}
		if(jRedises.isEmpty()){
			throw new RuntimeException("masters config error!" + masters);
		}
		jRedisShard.init(jRedises.size());
	}


	private JRedis getJRedis(byte[] key){
		return jRedises.get(jRedisShard.shard(key));
	}

	@Override
	public byte[] get(byte[] key) {
		return getJRedis(key).get(key);
	}

	@Override
	public void set(byte[] key, byte[] value) {
		getJRedis(key).set(key, value);
	}

	@Override
	public List<byte[]> mget(byte[]... keys) {
		List<byte[]> results = new ArrayList<byte[]>();
		for(byte[] key : keys){
			results.add(get(key));
		}
		return results;
	}

	@Override
	public boolean setnx(byte[] key, byte[] value) {
		return getJRedis(key).setnx(key, value);
	}

	@Override
	public void setex(byte[] key, int seconds, byte[] value) {
		getJRedis(key).setex(key, seconds, value);
	}

	@Override
	public void psetex(byte[] key, long millSeconds, byte[] value) {
		getJRedis(key).psetex(key, millSeconds, value);
	}

	@Override
	public void del(byte[] key) {
		getJRedis(key).del(key);
	}

	@Override
	public void del(byte[]... keys) {
		for(byte[] key : keys){
			del(key);
		}
	}

	@Override
	public long incr(byte[] key) {
		return getJRedis(key).incr(key);
	}

	@Override
	public long decr(byte[] key) {
		return getJRedis(key).decr(key);
	}

}
